import Axios from 'axios'

import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from "../views/Login/Login.vue";
import Home from "../views/Home/Home.vue";
import Luckdraw from '../views/Luckdraw/Luckdraw.vue';
import Setting from "../views/Setting/Setting.vue";

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect:'/login' },
  { path: '/login', name: 'Login', component: Login },
  { 
    path: '/home', 
    name: 'Home', 
    component: Home , 
    meta:{needLogin:true}, 
    redirect:"/luckdraw",
    children:[
      {
        path: '/luckdraw', name: 'Luckdraw', component: Luckdraw , meta:{needLogin:true},
      },
      {
        path: '/setting', name: 'Setting', component: Setting , meta:{needLogin:true},
      }
    ]
  },
]

const router = new VueRouter({
  routes
})


// 配置 router 拦截
// 前置
router.beforeEach((to,from,next) => {
  if(to.meta.needLogin){// 如果当前页面需要登录
    console.log("路由前置拦截:check token");
    // 检查token
    Axios.post("check_token").then(succ => {
      if(succ.data.status == 200){// token有效
        let str = JSON.stringify(succ.data)
        window.localStorage.setItem("userinfo",str);
        next();
      }else{
        console.log("路由前置拦截:token 失效");
        router.push("/login");
      }
    }).catch(err => {
      router.push("/login");
    })
  }else{
    next();
  }
});

// 后置
router.afterEach((to,from, next) => { 
  window.scrollTo(0,0)
})

export default router
